<template>
  <div class="box">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="flex-start"
          >
            <el-form-item
              v-if="userType == '00'"
              label="所属网点"
              prop="collectType"
            >
              <el-select
                v-model="form.collectType"
                placeholder="请选择所属网点"
                style="width: 275px"
                @change="gb"
              >
                <el-option
                  v-for="item in networkList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="time">
              <el-select
                v-model="form.dateType"
                placeholder="请选择时间"
                style="width: 150px"
                @change="timeechange"
              >
                <el-option
                  v-for="item in timee"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-date-picker
                v-model="form.time"
                style="width: 650px"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="mxDateChange"
              />
            </el-form-item>
            <el-form-item label="成本模式" prop="costModel">
              <el-select
                v-model="form.costModel"
                placeholder="请选择成本模式"
                style="width: 275px"
              >
                <el-option label="全部" value="1" />
                <el-option label="承包区模式" value="2" />
                <el-option label="直营客户模式" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="mxClear">重置</el-button>
              <el-button plain icon="el-icon-upload2" @click="exportData"
                >导出</el-button
              >
              <el-button plain icon="el-icon-setting" @click="openSetting"
                >承包区参数配置</el-button
              >
              <el-button plain icon="el-icon-setting" @click="openkhset"
                >客户参数配置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div v-if="!isObjectEmpty(tableData)">
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData.list.data"
            tooltip-effect="dark"
            :stripe="true"
            :highlight-current-row="true"
            :fit="true"
            row-key="id"
            :tree-props="{ children: 'children' }"
            max-height="600"
            border
          >
            <el-table-column
              v-for="(t, n) in tableData.fields"
              :key="n"
              :prop="t.fields"
              :label="t.translate"
              :fixed="n < 6"
              :min-width="
                flexColumnWidth(t.translate, t.fields, tableData.list.data)
              "
              align="center"
            >
              <template slot-scope="scope">
                <a
                  v-if="t.isPoint != null"
                  style="color: skyblue"
                  @click="searchDetail(scope.row, t)"
                  >{{ scope.row[t.fields] }}</a
                >
                <span v-else>{{ scope.row[t.fields] }}</span>
              </template>
              <el-table-column
                v-for="(s, i) in t.sunList"
                v-show="s.sunList != null"
                :key="i"
                :prop="s.fields"
                :label="s.translate"
                :min-width="
                  flexColumnWidth(s.translate, s.fields, tableData.list.data)
                "
                align="center"
              >
                <template slot-scope="scope">
                  <a
                    v-if="s.isPoint != null"
                    style="color: skyblue"
                    @click="searchDetail(scope.row, s)"
                    >{{ scope.row[s.fields] }}</a
                  >
                  <span v-else>{{ scope.row[s.fields] }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="isObjectEmpty(tableData)">
          <empty />
        </div>
      </el-col>
    </el-row>
    <div class="block" style="display: flex; justify-content: flex-end">
      <pagination
        :current-page="form.pageDate.pageNum"
        :page-size="form.pageDate.pageSize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 承包区配置参数弹框 -->
    <el-dialog
      title="承包区配置参数"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <el-form ref="updateParams" :model="updateParams" :rules="rules1">
        <el-form-item
          label="查询配置参数"
          :label-width="formLabelWidth"
          prop="contractAreaId"
        >
          <el-row>
            <el-col>
              <div style="width: 50%">
                <networkSelect
                  :value="'请选择所属网点'"
                  @networkCode="handleSelect"
                />
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="面单充值单价" :label-width="formLabelWidth">
          <el-input v-model="updateParams.sheetTopUpPrice" style="width: 50%" />
        </el-form-item>
        <el-form-item label="面单购进单价" :label-width="formLabelWidth">
          <el-input v-model="updateParams.sheetBuyPrice" style="width: 50%" />
        </el-form-item>
        <el-form-item label="包仓费" :label-width="formLabelWidth">
          <el-input
            v-model="updateParams.fixedWarehousingFee"
            style="width: 50%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="uodateParams">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 客户配置参数弹框 -->
    <el-dialog
      title="客户配置参数"
      :visible.sync="dialogFormVisible1"
      width="30%"
    >
      <el-form ref="upkhParams" :model="upkhParams" :rules="rules2">
        <el-form-item label="客户名称" :label-width="formLabelWidth" prop="id">
          <el-row>
            <el-col>
              <div style="width: 50%">
                <el-select
                  v-model="upkhParams.id"
                  placeholder="请选择"
                  @change="getprice"
                >
                  <el-option
                    v-for="item in khlist"
                    :key="item.value"
                    :label="item.clientName"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="面单购进单价" :label-width="formLabelWidth">
          <el-input v-model="upkhParams.sheetBuyPrice" style="width: 50%" />
        </el-form-item>
        <el-form-item label="面单充值单价" :label-width="formLabelWidth">
          <el-input v-model="upkhParams.sheetTopUpPrice" style="width: 50%" />
        </el-form-item>
        <el-form-item label="包仓费" :label-width="formLabelWidth">
          <el-input
            v-model="upkhParams.fixedWarehousingFee"
            style="width: 50%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="khParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOutletsList,
  getSubjectFirstList,
  getSubjectList,
  // subjectSearch,
  // addSubject,
} from "@/api/dashboard";
import empty from "@/components/menuComponent/empty.vue";
import networkSelect from "@/components/menuComponent/NetworkSelect.vue";
import { exportDataCG } from "@/api/home";
import {
  ContractingAreainit,
  selectSendDisposition,
  updateSendDisposition,
  getkhlist,
  getkhprice,
  xgkhparams,
} from "@/api/apifile/Networkfinance";
export default {
  components: { empty, networkSelect },
  data() {
    return {
      userType: localStorage.getItem("userType") || null,
      rules2: {
        id: [{ required: true, message: "请选择客户名称", trigger: "change" }],
      },
      rules1: {
        contractAreaId: [
          { required: true, message: "请选择配置参数", trigger: "change" },
        ],
      },
      flag: false,
      timee: [
        { value: 0, label: "扣付日期" },
        { value: 1, label: "会计日期" },
      ],
      searchForm: {
        contractArea: "",
        settleNetworkNameId: "",
        dateType: 0,
        type: "",
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      form: {
        collectType: 0,
        costModel: "",
        dateType: 0,
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      updateParams: {
        contractAreaId: null,
      },
      upkhParams: {
        id: "",
        sheetBuyPrice: null,
        sheetTopUpPrice: null,
        fixedWarehousingFee: null,
      },
      loading: false,
      formLabelWidth: "120px",
      // addForm: {
      //   networkNameId: '',
      //   firstId: '',
      //   secondName: ''
      // },
      // 客户的显示与隐藏
      isart: false,
      // 一级网点
      SubjectFirstList: [],
      // 网点列表
      networkList: [
        { value: 0, label: "网点" },
        { value: 1, label: "承包区" },
        { value: 2, label: "客户" },
      ],
      pages: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      currentPage4: 4,
      tableData: {
        list: {
          data: [],
        },
      },
      rules: {
        collectType: [
          { required: true, message: "请选择网点名称", trigger: "blur" },
        ],
        time: [{ required: true, message: "请选择日期", trigger: "blur" }],
      },
      khlist: [],
    };
  },
  async created() {
    this.khmclist();
  },
  methods: {
    // 根据id获取客户充值单价
    async getprice(value) {
      const res = await getkhprice(value);
      // console.log('价格', res)
      this.upkhParams.sheetTopUpPrice = res.data.sheetTopUpPrice;
      this.upkhParams.sheetBuyPrice = res.data.sheetBuyPrice;
      this.upkhParams.fixedWarehousingFee = res.data.fixedWarehousingFee;
    },
    // 获取客户名称列表
    async khmclist() {
      const res = await getkhlist();
      this.khlist = res.data;
    },
    // 确定修改时
    async khParams() {
      this.$refs.upkhParams.validate(async (valid) => {
        if (valid) {
          const res = await xgkhparams(this.upkhParams);
          this.dialogFormVisible1 = false;

          if (res.code === 200) {
            this.$message({
              message: `${res.data}`,
              type: "success",
            });
          } else {
            this.$message.error(`${res.data}`);
          }
        } else {
          return false;
        }
      });
    },
    timeechange(val) {
      // // console.log(val)
      this.searchForm.dateType = val;
    },
    searchDetail(item, type) {
      this.searchForm.contractArea = this.networkList.filter(
        (el) => el.value === this.form.collectType
      )[0].label;
      this.searchForm.settleNetworkNameId = item.contractAreaName;
      this.searchForm.type = type.isPoint;
      this.$store.state.app.searchData = this.searchForm;
      this.$store.state.app.name = "出港发件成本报表明细";
      this.$router.push({
        path: "ContractingAreaDetail",
      });
    },
    exportData() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.$notify.info({
            title: "开始准备下载...",
          });
          // this.init({ ...this.form, pageDate: this.pages })
          // // console.log(this.form)
          exportDataCG({ ...this.form, pageDate: this.pages }).then((res) => {
            const url = window.URL.createObjectURL(new Blob([res]), {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", "出港发件成本报表.xlsx"); // 设置下载的文件名
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
            this.$notify({
              title: "下载成功",
              type: "success",
            });
          });
        }
      });
    },

    isObjectEmpty(obj) {
      return Object.keys(obj).length === 0;
    },
    gb(value) {
      this.searchForm.collectType = value;
      if (value === 2) {
        this.isart = true;
      } else {
        this.isart = false;
      }
    },
    handleSizeChange(val) {
      this.form.pageDate.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.form.pageDate.pageNum = val;
      this.init();
    },
    mxClear() {
      this.$refs.form.resetFields();
      this.form.startTime = "";
      this.form.endTime = "";
    },
    search() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.init();
        }
      });
    },
    mxDateChange(value) {
      if (value != null) {
        this.form.startTime = value[0];
        this.form.endTime = value[1];
        this.searchForm.startTime = value[0];
        this.searchForm.endTime = value[1];
      }
    },
    init() {
      this.loading = true;

      ContractingAreainit(this.form).then((res) => {
        // console.log('查询', res)
        this.loading = false;

        if (res.code === 200) {
          this.tableData = res.data;
          this.total = res.data.list.total;
          this.$message.success("查询成功");
        } else {
          this.tableData = [];
          this.total = 0;
        }
      });
    },
    // ----------------------------
    // 获取网点列表
    getOutLet() {
      getOutletsList().then((res) => {
        if (res.code === 200) {
          this.networkList = res.data;
        }
      });
    },
    // 获取一级网点下拉框
    getSubjectFirst() {
      getSubjectFirstList().then((res) => {
        if (res.code === 200) {
          this.SubjectFirstList = res.data;
        }
      });
    },
    // 显示表格数据
    getList() {
      getSubjectList().then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.data;
          this.total = res.data.total;
          this.pages = res.data.pages;
        } else {
          this.$message({
            message: res.msg,
            type: "warning",
          });
        }
      });
    },
    // 打开配置弹窗
    openSetting() {
      this.dialogFormVisible = true;
    },
    // 打开配置弹窗
    openkhset() {
      this.dialogFormVisible1 = true;
    },
    handleSelect(val) {
      // console.log('选择', val)
      this.updateParams.contractAreaId = val;
      this.getSelectContractAreaSend(val);
    },

    // 获取承包区配置
    getSelectContractAreaSend(contractAreaId) {
      // console.log('contractAreaId:', contractAreaId)
      selectSendDisposition(contractAreaId).then((res) => {
        if (res.code === 200) {
          if (res.data === null) {
            this.updateParams = {};
            return;
          }
          this.updateParams = res.data;
          // console.log('res', res)
        }
      });
    },
    // 修改承包区配置
    uodateParams() {
      this.$refs.updateParams.validate((valid) => {
        if (valid) {
          updateSendDisposition(this.updateParams).then((res) => {
            if (res.code === 200) {
              this.dialogFormVisible = false;
              this.$message("修改成功，正在更新数据");
              // this.init()
            }
          });
        } else {
          return false;
        }
      });
    },
    // 重置
    clear() {
      this.form = {};
      this.getList();
    },

    handleSelectionChange(val) {
      // this.multipleSelection = val;
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.flex-start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.flex-bettom {
  display: flex;
  justify-content: space-between;
}

.header {
  padding-bottom: 20px;
  border-bottom: 1px solid #ccc;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
